import uuid

from django.shortcuts import render,redirect
from django.views import View
from django.utils.decorators import method_decorator

from utils.resFormatUtil import ResFormat
from cyxmall.settings import alipay
from commodity.models import CommodityInfo
from utils.verifyUtil import verifyParam
from .models import Order
from apps.user.models import User_info
# Create your views here.

class OrderView(View):
	
	def get(self, request):
		data = request.GET.dict()
		signature = data.pop('sign')
		res = alipay.verify(data,signature)
		status_code = 2
		if res:
			status_code = 1
		order_no = data.pop('out_trade_no')
		order = Order.objects.filter(order_no=order_no)[0]
		order.status = status_code
		order.save()
		
		return redirect('/static/index.html')
	
	@method_decorator(verifyParam('option_id','subject'))
	def post(self, request):
		post = request.POST # ajax传过来的
		id = post.get('id')
		option_id = post.get('option_id')
		order_no = str(uuid.uuid4())
		subject = post.get('subject')
		money = CommodityInfo.objects.filter(id=option_id)
		if not money:
			return ResFormat(status='PARAM_ERROR').json_response()
		money = money[0].price
		# 获取订单信息
		commodity_id = id
		user_query = User_info.objects.filter(state=0,email=request.email)
		if not user_query:
			return ResFormat(status='PARAM_ERROR').json_response()
		user_id = user_query[0].id
		# 存入数据库
		Order.objects.create(order_no=order_no,money=money,subject=subject,commodity_id=commodity_id,user_id=user_id)
		
		order_param = alipay.api_alipay_trade_page_pay(
			out_trade_no=order_no,
			total_amount=money,
			subject=subject,
			return_url='http://127.0.0.1:8000/order/alipay/'
		)
		# 构造支付url:支付宝网关 + 订单参数
		pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_param
		
		return ResFormat(data=pay_url).json_response()
